package com.qdlc.p2p.dal.dao.impl;

import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.qdlc.p2p.common.exception.BorrowException;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.dao.jpa.BaseDaoImpl;
import com.qdlc.p2p.dal.common.model.jpa.OrderFilter.OrderType;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.common.model.jpa.SearchFilter.Operators;
import com.qdlc.p2p.dal.dao.MovieConfigDao;
import com.qdlc.p2p.dal.dto.MovieConfig;
import com.qdlc.p2p.dal.model.MovieConfigModel;

@Repository("")
public class MovieConfigDaoImpl extends BaseDaoImpl<MovieConfig> implements MovieConfigDao {

	@Override
	public PageDataList<MovieConfig> list(MovieConfigModel model) {
		QueryParam param = QueryParam.getInstance();
		if (model != null) {
			if(!StringUtil.isBlank(model.getSearchName())){//模糊查询条件
				param.addParam("name", Operators.LIKE, model.getSearchName().trim());
			}
			param.addPage(model.getPage(), model.getSize());
		}
		param.addOrder(OrderType.DESC, "id");

		return super.findPageList(param);
	}

	@Override
	public List<MovieConfig> findAll() {
		QueryParam param = QueryParam.getInstance().addParam("enable", true).addOrder(OrderType.DESC, "id");
		return findByCriteria(param);
	}
	
    public void updateByMoviePages(int moviePages, long id) {
        String jpql = "UPDATE MovieConfig SET sellAcount = sellAcount + :moviePages WHERE id = :id";
        Query query = em.createQuery(jpql);
        query.setParameter("moviePages", moviePages);
        query.setParameter("id", id);
        int count = query.executeUpdate();
        if (count < 1) {
            throw new BorrowException("购票失败！该影片可能已售罄", 1);
        }
        super.refresh(find(id));
    }

}
